package config

import (
	"fmt"
	"io"
	"net"
	"os"
)

func LoadConfig() Sender {
	if len(os.Args) != 3 {
		fmt.Println(" Exception Params len is not 2 !")
	}
	fmt.Println("file:", os.Args[1], " host:", os.Args[2])
	sender := Sender{os.Args[1], os.Args[2]} //传入文件名和主机+端口
	return sender
}

type Sender struct {
	FilePath string
	Endpoint string
}

func (s Sender) Start() {
	s.Check()
}

func (s Sender) Check() {
	info, e1 := os.Stat(s.FilePath) //检查文件是否正常
	AssertError(e1)

	conn, e2 := net.Dial("tcp", s.Endpoint)
	AssertError(e2)
	conn.Write([]byte(info.Name())) //连接后写入文件名

	buf := make([]byte, 1024)
	n, e3 := conn.Read(buf) //读取返回值
	AssertError(e3)
	fmt.Println("check", string(buf[:n]))
	if "ok" == string(buf[:n]) { //如果收到是ok就开始写
		s.Action(s.FilePath, conn)
		defer conn.Close()
	}
}

func (s Sender) Action(path string, conn net.Conn) {
	fmt.Println("action", path, s.Endpoint)
	file, e := os.Open(path) //打开文件
	AssertError(e)

	buf := make([]byte, 4*1024)
	for {
		n, err := file.Read(buf)
		if err == io.EOF || n == 0 {
			fmt.Println("Send File finished")
			return
		}
		AssertError(err)
		conn.Write(buf[:n])
	}
	defer file.Close()
}

func AssertError(e error) {
	if e != nil {
		fmt.Println("AssertError Exception: ", e)
		return
	}
}
